package ch.usi.inf.pf2.gui.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.JComponent;
import javax.swing.JFileChooser;

import ch.usi.inf.pf2.gui.JSpreadSheetGUI;
import ch.usi.inf.pf2.gui.SpreadSheetFileManager;

/**
 * Listener for the menu and button "Save As"
 * 
 * @author Lorenzo Baracchi, Ebrisa Savina Mastrodicasa
 *
 */
public class SaveAsActionListener implements ActionListener
{
    private JSpreadSheetGUI spreadTable;
    private static ArrayList<JComponent> component = new ArrayList<JComponent>();
    private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
    
    public SaveAsActionListener (JSpreadSheetGUI spreadTable, JComponent component)
    {
	   super();
	   this.spreadTable=spreadTable;
	   this.component.add(component);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
	   if(spreadTable.getSheet() != null)
	   {
		   int returnValue = fileChooser.showSaveDialog(spreadTable.getFrame());
		   if(returnValue != JFileChooser.APPROVE_OPTION)
		   {
			   return;
		   }
		   else
		   {
			   File selectedFile = fileChooser.getSelectedFile();
			   SpreadSheetFileManager.saveAsFile(spreadTable.getSheet(), selectedFile.getName());
			   spreadTable.getSheet().setName(selectedFile.getName());
			   for(JComponent c : component)
				  c.setEnabled(true);
			   spreadTable.getFrame().setTitle("SpreadSheet - " + spreadTable.getSheet().getName());
		   }
	   }
	   spreadTable.getSheet().setHasBeenSaved(true);
    }

}
